package com.kx.kxpicture.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kx.kxpicture.exception.BusinessException;
import com.kx.kxpicture.exception.ErrorCode;
import com.kx.kxpicture.exception.ThrowsUtils;
import com.kx.kxpicture.model.dto.space.SpaceAddRequest;
import com.kx.kxpicture.model.dto.space.SpaceQueryRequest;
import com.kx.kxpicture.model.entity.Picture;
import com.kx.kxpicture.model.entity.Space;
import com.kx.kxpicture.model.entity.SpaceUser;
import com.kx.kxpicture.model.entity.User;
import com.kx.kxpicture.model.enums.SpaceLevelEnum;
import com.kx.kxpicture.model.enums.SpaceRoleEnum;
import com.kx.kxpicture.model.enums.SpaceTypeEnum;
import com.kx.kxpicture.model.vo.PictureVO;
import com.kx.kxpicture.model.vo.SpaceVO;
import com.kx.kxpicture.model.vo.SpaceVO;
import com.kx.kxpicture.model.vo.UserVO;
import com.kx.kxpicture.service.SpaceService;
import com.kx.kxpicture.mapper.SpaceMapper;
import com.kx.kxpicture.service.SpaceUserService;
import com.kx.kxpicture.service.UserService;
import org.aspectj.weaver.IUnwovenClassFile;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
* @author kuang
* @description 针对表【space(空间)】的数据库操作Service实现
* @createDate 2025-09-07 15:58:48
*/
@Service
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space>
    implements SpaceService{

    @Resource
    UserService userService;

    @Resource
    TransactionTemplate transactionTemplate;

    @Resource
    SpaceUserService spaceUserService;

    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        QueryWrapper<Space> queryWrapper = new QueryWrapper<>();
        if (spaceQueryRequest == null) {
            return queryWrapper;
        }
        Long id = spaceQueryRequest.getId();
        Long userId = spaceQueryRequest.getUserId();
        String spaceName = spaceQueryRequest.getSpaceName();
        Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
        Integer spaceType = spaceQueryRequest.getSpaceType();

        String sortField = spaceQueryRequest.getSortField();
        String sortOrder = spaceQueryRequest.getSortOrder();
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(spaceName), "spaceName", spaceName);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceLevel), "spaceLevel", spaceLevel);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceType), "spaceType", spaceType);

        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 用户创建空间
     * @param spaceAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public long addSpace(SpaceAddRequest spaceAddRequest, User loginUser) {
        //1填充参数默认值
        Space space = new Space();
        BeanUtils.copyProperties(spaceAddRequest,space);
        if (StrUtil.isBlank(space.getSpaceName())){
            space.setSpaceName("默认空间");
        }
        if (ObjUtil.isEmpty(space.getSpaceLevel())){
            space.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }
        if (ObjUtil.isEmpty(space.getSpaceType())){
            space.setSpaceType(SpaceTypeEnum.PRIVATE.getValue());
        }
        fillSpaceBySpaceLevel(space);
        //2校验参数
        validSpace(space,true);
        //3校验权限，非管理员只能创建普通级别的空间
        Long userId = loginUser.getId();
        space.setUserId(userId);
        if (!space.getSpaceLevel().equals(SpaceLevelEnum.COMMON.getValue()) && !userService.isAdmin(loginUser)){
            throw  new BusinessException(ErrorCode.PARAMS_ERROR,"无权限创建指定级别空间");
        }
        //4控制同一用户只能创建一个私有空间,加锁实现
//        String lock = String.valueOf(userId).intern();\
        //使用currenthashmap存储锁
        ConcurrentHashMap<Long,Object> concurrentHashMap = new ConcurrentHashMap<>();
        Object lock = concurrentHashMap.computeIfAbsent(userId, key -> new Object());
        Long executed = transactionTemplate.execute((status -> {
            synchronized (lock) {
                try {
                    //判断是否已存在空间 团队空间和私人空间都只能存在一个
                    boolean exists = this.lambdaQuery()
                            .eq(Space::getUserId, userId)
                            .eq(Space::getSpaceType,space.getSpaceType())
                            .exists();
                    if (exists) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "每类空间只能存在一个");
                    }
                    boolean save = this.save(space);
                    if (!save) {
                        throw new BusinessException(ErrorCode.OPERATION_ERROR);
                    }
                    //创建成功后，如果是团队空间，关联新增团队成员记录
                    if (SpaceTypeEnum.TEAM.getValue()==space.getSpaceType()){
                        SpaceUser spaceUser=new SpaceUser();
                        spaceUser.setSpaceId(space.getId());
                        spaceUser.setUserId(userId);
                        spaceUser.setSpaceRole(SpaceRoleEnum.ADMIN.getValue());
                        boolean result = spaceUserService.save(spaceUser);
                        ThrowsUtils.throwIf(!result, ErrorCode.OPERATION_ERROR,"创建团队空间记录失败");
                    }
                    return space.getId();
                } finally {
                    concurrentHashMap.remove(userId);
                }
            }
        }));
        return Optional.ofNullable(executed).orElse(-1L);
    }

    @Override
    public SpaceVO getSpaceVO(Space space, HttpServletRequest request) {

        SpaceVO pictureVO = SpaceVO.objToVo(space);
        Long userId = space.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserToVo(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    @Override
    public Page<SpaceVO> getSpaceVOPage(Page<Space> spacePage, HttpServletRequest request) {
        List<Space> spaceList = spacePage.getRecords();
        Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
        if (CollUtil.isEmpty(spaceList)) {
            return spaceVOPage;
        }

        List<SpaceVO> spaceVOList = spaceList.stream().map(SpaceVO::objToVo).collect(Collectors.toList());

        Set<Long> userIdSet = spaceList.stream().map(Space::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));

        spaceVOList.forEach(spaceVO -> {
            Long userId = spaceVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            spaceVO.setUser(userService.getUserToVo(user));
        });
        spaceVOPage.setRecords(spaceVOList);
        return spaceVOPage;
    }

    @Override
    public void validSpace(Space space, boolean add) {
        ThrowsUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR);

        String spaceName = space.getSpaceName();
        Integer spaceLevel = space.getSpaceLevel();
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);
        Integer spaceType = space.getSpaceType();
        SpaceTypeEnum spaceTypeEnum = SpaceTypeEnum.getEnumByValue(spaceLevel);
        if (add) {
            if (StrUtil.isBlank(spaceName)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间名称不能为空");
            }
            if (spaceLevel == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间级别不能为空");
            }
            if (spaceType==null){
                throw  new BusinessException(ErrorCode.PARAMS_ERROR,"空间类别不能为空");
            }
        }

        if (spaceLevel != null && spaceLevelEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间级别不存在");
        }
        if (StrUtil.isNotBlank(spaceName) && spaceName.length() > 30) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间名称过长");
        }
    }

    @Override
    public void fillSpaceBySpaceLevel(Space space) {
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(space.getSpaceLevel());
        if (spaceLevelEnum != null) {
            long maxSize = spaceLevelEnum.getMaxSize();
            if (space.getMaxSize() == null) {
                space.setMaxSize(maxSize);
            }
            long maxCount = spaceLevelEnum.getMaxCount();
            if (space.getMaxCount() == null) {
                space.setMaxCount(maxCount);
            }
        }
    }

    @Override
    public void checkSpaceAuth(User loginUser, Space space) {
        if (!space.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
    }
}




